// 导入 express 模块
const express = require("express");
const fs = require("fs");
const path = require("path");

// 创建应用对象
const app = express();

// 声明中间件函数
function recordMiddleware(req, res, next) {
  let { url, ip } = req;
  fs.appendFileSync(
    path.resolve(__dirname, "./access.log"),
    `${url} ${ip}\r\n`,
  );
  next();
}

app.use(recordMiddleware);

// 创建路由
app.get("/home", (req, res) => {
  res.send("前台首页");
});

app.get("/admin", (req, res) => {
  res.send("后台首页");
});

app.all("*", (req, res) => {
  res.send("<h1>404 Not Found</h1>");
});

// 监听端口，启动服务
app.listen("8000", () => {
  console.log("服务已经启动……全局中间件");
});
